//
//  SJMyZeroViewController.m
//  WSL
//
//  Created by CJ on 2017/11/16.
//  Copyright © 2017年 sanjuetech. All rights reserved.
//

#import "SJMyZeroViewController.h"
#import "SJWordItem.h"
#import "SJExtraItem.h"
#import "SJOneCell.h"
#import "SJCustomLayout.h"
#import "SJTreeApi.h"
#import "SJMovePosApi.h"
#import "SJSpaceStationAddApi.h"
#import "SJDelBlockApi.h"

#import "JTSImageViewController.h"
#import "JTSImageInfo.h"

#import <JPVideoPlayer/UIView+WebVideoCache.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

#import "SJUploadBar.h"
#import "SJFunctionBar.h"
#import "SJOtherFunctionBar.h"
#import "SJTreeViewController.h"
#import "SJSpaceStationViewController.h"
#import "SJAddWordViewController.h"
#import "SJAddPicViewController.h"
#import "SJAddFromSSViewController.h"
#import "SJAddTxtViewController.h"
#import "SJTxtDetailViewController.h"
#import "SJEditTxtViewController.h"
#import "SJEditPicViewController.h"
#import "SJEditAudioViewController.h"
#import "SJEditVideoViewController.h"
#import "SJEditWordViewController.h"

@interface SJMyZeroViewController () <UICollectionViewDataSource, UICollectionViewDelegate, SJCustomLayoutDelegate, JTSImageViewControllerAnimationDelegate, JPVideoPlayerDelegate, SJUploadBarDelegate>

@property (strong, nonatomic) UIButton *displayButton;
@property (nonatomic, copy) NSString *isDisplayTitle;


////////////////////////////////////

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) int page;

@property (strong, nonatomic) SJCustomLayout *customLayout;

@property (nonatomic, copy) NSString *t;
@property (nonatomic, copy) NSString *l;
@property (nonatomic, copy) NSString *w;
@property (nonatomic, copy) NSString *h;

@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGesture;
@property (nonatomic, copy) NSString *isMove;
@property (nonatomic, strong) UIView *snapshot;
@property (nonatomic, strong) SJOneCell *selectedCell;
@property (nonatomic, assign) CGPoint touchPoint;
@property (nonatomic, copy) NSString *autoScrollDirection; // 1:上 2:下
@property (nonatomic, strong) CADisplayLink *autoScrollTimer;
@property (nonatomic, strong) NSIndexPath *selectedIndexPath;

// 视频
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) SJWordItem *selectedItem;
@property (nonatomic, strong) UIView *videoContainer;

@property (nonatomic, strong) UIView *detailImageView;
@property (strong, nonatomic) UILabel *detailLabel;

@property (strong, nonatomic) NSMutableArray *optionArray;
@property (strong, nonatomic) JTSImageViewController *imageViewer;


@property (nonatomic, strong) UIView *touchView;

// 功能版
@property (nonatomic, strong) UIView *funcView;

@property (nonatomic, strong) UIView *navigationBarView; // 背景

// 快的最下边
@property (nonatomic, assign) int bottomNum;

@end

@implementation SJMyZeroViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [SJStatisticTool beginLogPageView:NSStringFromClass([self class])];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [SJStatisticTool endLogPageView:NSStringFromClass([self class])];
}

- (void)dealloc {
    SJLogFunc;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self stopAutoScrollTimer];
}

- (void)didAddZeroWordNotification:(NSNotification *)notification {
    
    SJWordItem *item = notification.userInfo[@"item"];
    [self.dataArray addObject:item];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.dataArray.count - 1 inSection:0];
    [self.collectionView insertItemsAtIndexPaths:@[indexPath]];
    
    NSString *imageName = @"guide_edit";
    if (812 == SJScreenH) {
        imageName = [NSString stringWithFormat:@"%@-x", imageName];
    }
    
    if ([SJGuideView shouldShowGuider:imageName]) {
        [SJGuideView guideViewWithImageName:imageName];
    }
}

- (void)didEditWordNotification:(NSNotification *)notification {
    
    SJWordItem *item = notification.userInfo[@"item"];
    
    for (SJWordItem *wItem in self.dataArray) {
        if ([item.ID isEqualToString:wItem.ID]) {
            [self.dataArray removeObject:wItem];
            [self.dataArray addObject:item];
            [self.collectionView reloadData];
            break;
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didAddZeroWordNotification:) name:SJDidAddZeroWordNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEditWordNotification:) name:SJDidEditWordNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeNode) name:UIApplicationWillResignActiveNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didLogin) name:SJDidLoginNotification object:nil];
    
    self.bottomNum = 0;
    self.isDisplayTitle = @"0";
    self.page = 0;
    [self setupUI];
    [self loadNewData];
}

- (void)didLogin {
    
    [self loadNewData];
    
    NSString *imageName = @"guide_new_position";
    if (812 == SJScreenH) {
        imageName = [NSString stringWithFormat:@"%@-x", imageName];
    }
    
    if ([SJGuideView shouldShowGuider:imageName]) {
        [SJGuideView guideViewWithImageName:imageName];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (![SJUserDefaults objectForKey:SJToken]) {
        [self login];
    }
}

- (void)setupUI {
    
    
    [self.view addSubview:self.collectionView];
    self.collectionView.sd_layout
    .leftSpaceToView(self.view, SJLayoutFrame(0))
    .topSpaceToView(self.view, SJLayoutFrame(0))
    .rightSpaceToView(self.view, SJLayoutFrame(0))
    .bottomSpaceToView(self.view, SJLayoutFrame(0));
    
//    [self.view addSubview:self.navigationBarView];
//
//    if (812 == SJScreenH) {
//        self.navigationBarView.sd_layout
//        .leftSpaceToView(self.view, SJLayoutFrame(0))
//        .topSpaceToView(self.view, SJLayoutFrame(40))
//        .heightIs(SJLayoutFrame(50))
//        .widthIs(SJScreenW);
//    } else {
//        self.navigationBarView.sd_layout
//        .leftSpaceToView(self.view, SJLayoutFrame(0))
//        .topSpaceToView(self.view, SJLayoutFrame(0))
//        .heightIs(SJLayoutFrame(50))
//        .widthIs(SJScreenW);
//    }
}

#pragma mark - getter

- (UIView *)navigationBarView{
    
    if (!_navigationBarView) {
        
        _navigationBarView = [UIView new];
        _navigationBarView.backgroundColor = [UIColor clearColor];
        
        UIButton *buttonItem_0 = [UIButton buttonWithType:UIButtonTypeCustom];
        [buttonItem_0 setImage:[UIImage imageNamed:@"sicang_icon_sicang"] forState:UIControlStateNormal];
        [buttonItem_0 setImage:[UIImage imageNamed:@"sicang_icon_sicang"] forState:UIControlStateSelected];
        buttonItem_0.tag = 0;
        buttonItem_0.selected = YES;
        
        [_navigationBarView addSubview:buttonItem_0];
        
        buttonItem_0.sd_layout
        .centerYEqualToView(_navigationBarView)
        .heightIs(SJLayoutFrame(40))
        .widthIs(SJLayoutFrame(40))
        .leftSpaceToView(_navigationBarView, SJLayoutFrame(30));
        
    }
    return _navigationBarView;
}

- (UIView *)touchView {
    
    if (!_touchView) {
        
        _touchView = [UIView new];

        UIImageView *touchImageView = [UIImageView new];
        touchImageView.image = [UIImage imageNamed:@"sicang_icon_position"];
        
        [_touchView addSubview:touchImageView];
        touchImageView.sd_layout.spaceToSuperView(UIEdgeInsetsZero);
        
    }
    return _touchView;
}

- (UIButton *)displayButton {
    
    if (!_displayButton) {
        
        _displayButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_displayButton setImage:[UIImage imageNamed:@"btn_displaytitle_nor"] forState:UIControlStateNormal];
        [_displayButton setImage:[UIImage imageNamed:@"btn_displaytitle_sel"] forState:UIControlStateSelected];
        [_displayButton addTarget:self action:@selector(displayAction) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _displayButton;
}

- (void)displayAction {
    
    self.displayButton.selected = !self.displayButton.selected;
    if (self.displayButton.selected) {
        self.isDisplayTitle = @"1";
    } else {
        self.isDisplayTitle = @"0";
    }
    [self.collectionView reloadData];

//    WeakSelf;
//    [TYSnapshot screenSnapshot:self.collectionView finishBlock:^(UIImage *snapShotImage) {
//
//        [weakSelf saveImage:snapShotImage];
//    }];
    
}

- (void)saveImage:(UIImage *)image {
    //save to photosAlbum
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    NSString *barItemTitle = @"保存成功";
    if (error != nil) {
        barItemTitle = @"保存失败";
    }
    
    SJLog(@"%@", barItemTitle);
    
}


- (UIView *)detailImageView{
    
    if (!_detailImageView) {
        
        _detailImageView = [UIView new];
        _detailImageView.backgroundColor = SJColorHexString(@"#00000090");
        _detailImageView.alpha = 0;
        
        
        UIButton * moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [moreButton setImage:[UIImage imageNamed:@"detail_btn_more_nor"] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(moreAction) forControlEvents:UIControlEventTouchUpInside];
        
//        [_detailImageView addSubview:moreButton];
//        moreButton.sd_layout
//        .centerYEqualToView(_detailImageView)
//        .rightSpaceToView(_detailImageView, SJLayoutFrame(5))
//        .heightIs(SJLayoutFrame(40))
//        .widthIs(SJLayoutFrame(40));
        
        [_detailImageView addSubview:self.detailLabel];
        self.detailLabel.sd_layout.spaceToSuperView(UIEdgeInsetsMake(SJLayoutFrame(9), SJLayoutFrame(13), SJLayoutFrame(9), SJLayoutFrame(50)));
        
        
    }
    return _detailImageView;
}

- (void)functionBar:(SJFunctionBar *)uploadBar didSelectItemAtIndex:(NSInteger)index {
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 编辑
            
            [weakSelf editItem];
        }
        
        if (index == 1) { // 移入收藏
            [weakSelf moveToFavorite];
        }
        
        if (index == 2) { // 副本收藏
            [weakSelf cpToFavorite];
        }
        
    }];
}

- (void)otherFunctionBar:(SJOtherFunctionBar *)uploadBar didSelectItemAtIndex:(NSInteger)index {
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 副本收藏
            if ([weakSelf.selectedItem.can_fav isEqualToString:@"1"]) {
                
                [SVProgressHUD showInfoWithStatus:@"内容受作者保护"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                return;
            }
            
            [weakSelf cpToFavorite];
        }
        
    }];
}

- (void)editFilter {
    
    // 检索
    int max_t = 0;
    for (SJWordItem *item in self.dataArray) {
        
        if ([item.t intValue] >= max_t) {
            max_t = [item.t intValue] + [item.h intValue];
        }
    }
    
    NSMutableArray *arrlt = [NSMutableArray array]; // 二维
    int max_w = SJItemCount;
    for (int i = 0; i < max_t + max_w; i++) {
        
        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [arrlt addObject:arrl];
        
        for (int j = 0; j < max_w; j++) {
            arrlt[i][j] = @0;
        }
    }
    
    for (SJWordItem *item in self.dataArray) {
        
        if (item == self.selectedItem) {
            continue;
        }
        
        int t = [item.t intValue];
        int l = [item.l intValue];
        int w = [item.w intValue];
        int h = [item.h intValue];
        
        for (int i = t; i < t + h; i++) {
            
            for (int j = l; j < l + w; j++) {
                arrlt[i][j] = @1;
            }
        }
    }
    
    int l2r = 0;
    NSMutableArray *optArray = [NSMutableArray array];
    
    if ([self.selectedItem.t intValue] >= arrlt.count - max_w) {
        
        int maxOptW = max_w - [self.selectedItem.l intValue];
        int maxOptH = max_w;
        
        for (int i = 0; i < maxOptH; i++) {
            
            for (int j = 0; j < maxOptW; j++) {
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = [NSString stringWithFormat:@"%d", i + 1];
                dict[@"w"] = [NSString stringWithFormat:@"%d", j + 1];
                [optArray addObject:dict];
            }
        }
        
    } else {
        
        for (int i = [self.selectedItem.l intValue]; i < max_w; i++) { // 第1行
            
            if ([arrlt[[self.selectedItem.t intValue]][i] isEqualToNumber: @0]) {
                
                l2r = i - [self.selectedItem.l intValue] + 1;
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = @"1";
                dict[@"w"] = [NSString stringWithFormat:@"%d", l2r];
                [optArray addObject:dict];
                
            } else {
                break;
            }
        }
        
        for (int n = 1; n < max_w; n++) { // 2 ~ max_w 行
            
            for (int i = [self.selectedItem.l intValue]; i < max_w; i++) {
                
                if ([arrlt[[self.selectedItem.t intValue] + n][i] isEqualToNumber: @0]) {
                    
                    if (i - [self.selectedItem.l intValue] + 1 <= l2r) {
                        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                        dict[@"h"] = [NSString stringWithFormat:@"%d", n + 1];
                        dict[@"w"] = [NSString stringWithFormat:@"%d", i - [self.selectedItem.l intValue] + 1];
                        [optArray addObject:dict];
                    } else {
                        break;
                    }
                    
                } else {
                    l2r = i - [self.selectedItem.l intValue];
                    break;
                }
            }
        }
    }
    
    if (optArray.count == 0) {
        return;
    }
    
    self.optionArray = optArray;
    
}

- (void)moreAction {
    
    if ([self.selectedItem.is_me isEqualToString:@"1"]) { // 自己
        
//        SJFunctionBar *functionBar = [[SJFunctionBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(85))];
//        functionBar.delegate = self;
//
//        [LEEAlert actionsheet].config
//        .LeeAddCustomView(^(LEECustomView *custom) {
//            custom.view = functionBar;
//        })
//        .LeeCornerRadius(SJCornerRadius)
//        .LeeHeaderColor([UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]])
//        .LeeActionSheetBottomMargin(SJLayoutFrame(7))
//        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
//            return SJScreenW - SJLayoutFrame(14);
//        })
//        .LeeHeaderInsets(UIEdgeInsetsZero)
//        .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
//        .LeeShow();
        
    } else {
        
//        SJOtherFunctionBar *functionBar = [[SJOtherFunctionBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(85))];
//        functionBar.delegate = self;
//
//        [LEEAlert actionsheet].config
//        .LeeAddCustomView(^(LEECustomView *custom) {
//            custom.view = functionBar;
//        })
//        .LeeCornerRadius(SJCornerRadius)
//        .LeeHeaderColor([UIColor colorWithPatternImage:[UIImage imageNamed:@"home_bg"]])
//        .LeeActionSheetBottomMargin(SJLayoutFrame(7))
//        .LeeConfigMaxWidth(^CGFloat(LEEScreenOrientationType type) {
//            return SJScreenW - SJLayoutFrame(14);
//        })
//        .LeeHeaderInsets(UIEdgeInsetsZero)
//        .LeeBackgroundStyleBlur(UIBlurEffectStyleDark)
//        .LeeShow();
    }
    
}

- (UILabel *)detailLabel {
    
    if (!_detailLabel) {
        
        _detailLabel = [UILabel new];
        _detailLabel.textColor = SJColorHexString(@"#ffffffff");
        _detailLabel.font = [UIFont systemFontOfSize:SJLayoutFrame(12)];
        _detailLabel.textAlignment = NSTextAlignmentLeft;
        _detailLabel.numberOfLines = 0;
        
    }
    return _detailLabel;
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        
        _dataArray = [[NSMutableArray alloc] init];
        
    }
    return _dataArray;
}

- (UILongPressGestureRecognizer *)longPressGesture {
    
    if (!_longPressGesture) {
        
        _longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
        _longPressGesture.minimumPressDuration = .3;
        
    }
    return _longPressGesture;
}

- (UICollectionView *)collectionView {
    
    if (!_collectionView) {
        
        // 首页
        self.customLayout = [[SJCustomLayout alloc] init];
        self.customLayout.delegate = self;
        
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:self.customLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.contentInset = UIEdgeInsetsMake(SJMargin, 0, 0, 0);
        
        [_collectionView registerClass:[SJOneCell class] forCellWithReuseIdentifier:NSStringFromClass([SJOneCell class])];
        
        // header
        _collectionView.mj_header = [SJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        // footer
        _collectionView.mj_footer = [SJDIYFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        
        [_collectionView addGestureRecognizer:self.longPressGesture];
        
    }
    
    return _collectionView;
}

- (void)showTrash {
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    [self.view addSubview:self.funcView];
    
    if (812 == SJScreenH) {
        self.funcView.sd_layout
        .bottomSpaceToView(self.view, SJLayoutFrame(11) + 18)
        .leftSpaceToView(self.view, SJLayoutFrame(17))
        .widthIs(SJScreenW - SJLayoutFrame(34))
        .heightIs(SJLayoutFrame(60));
    } else {
        self.funcView.sd_layout
        .bottomSpaceToView(self.view, SJLayoutFrame(11))
        .leftSpaceToView(self.view, SJLayoutFrame(17))
        .widthIs(SJScreenW - SJLayoutFrame(34))
        .heightIs(SJLayoutFrame(60));
    }
    
    [UIView animateWithDuration:.25 animations:^{
        self.funcView.alpha = 1;
    }];
}

- (void)hideTrash {
    
    [UIView animateWithDuration:.25 animations:^{
        self.funcView.alpha = 0;
    } completion:^(BOOL finished) {
        [self.funcView removeFromSuperview];
        self.funcView = nil;
    }];
}

- (void)longPressAction:(UILongPressGestureRecognizer *)gesture {
    
    switch (gesture.state) { // 移动
            
        case UIGestureRecognizerStateBegan: {
            
            self.tabBarController.tabBar.hidden = YES;
            
            CGPoint touchPoint = [gesture locationInView:self.collectionView];
            NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:touchPoint];
            self.touchPoint = touchPoint;
            
            if (touchIndexPath) {
                
                [self cellSelectedAtIndexPath:touchIndexPath];
                
                // 显示废纸篓
                [self showTrash];
                
            } else {
                
                NSInteger l = (NSInteger)(touchPoint.x / ((SJScreenW - SJMargin) / SJItemCount));
                NSInteger t = (NSInteger)((touchPoint.y + SJMargin) / ((SJScreenW - SJMargin) / SJItemCount));
                
                self.l = [NSString stringWithFormat:@"%ld", (long)l];
                self.t = [NSString stringWithFormat:@"%ld", (long)t];
                
                // 添加新的
                [self addItem];
                
            }
        }
            break;
        case UIGestureRecognizerStateChanged: {
            
            if (self.snapshot) {
                
                CGPoint touchPoint = [gesture locationInView:self.collectionView];
                [self gestureChangedAtPoint:touchPoint];
                
                touchPoint = [self.collectionView convertPoint:touchPoint toView:self.view];
                
                if (CGRectContainsPoint(self.funcView.frame, touchPoint)) { // 功能版
                    
                    [self funcChangedAction:touchPoint];
                    
                } else {
                    
                    for (UIButton *btn in self.funcView.subviews) {
                        btn.selected = NO;
                    }
                }
            }
        }
            break;
        case UIGestureRecognizerStateEnded: {

            if (self.snapshot) {
                
                self.tabBarController.tabBar.hidden = NO;
                
                CGPoint touchPoint = [gesture locationInView:self.collectionView];
                touchPoint = [self.collectionView convertPoint:touchPoint toView:self.view];
                
                [self.collectionView removeGestureRecognizer:self.longPressGesture];
                if (CGRectContainsPoint(self.funcView.frame, touchPoint)) { // 功能版
//                    [self deleteItem];
                    [self funcAction:touchPoint];
                    
                } else { // 移动
                    [self gestureEnded];
                    [self hideTrash];
                }
            }
        }
            break;
            
        default:
            break;
    }
}

- (void)funcChangedAction:(CGPoint)point {
    
    CGPoint touchPoint = [self.view convertPoint:point toView:self.funcView];
    
    for (UIButton *btn in self.funcView.subviews) {
        
        btn.selected = NO;
        if (CGRectContainsPoint(btn.frame, touchPoint)) {
            
            btn.selected = YES;
        }
    }
}


- (UIView *)funcView {
    
    if (!_funcView) {
        
        _funcView = [UIView new];
        _funcView.backgroundColor = [UIColor clearColor];
        _funcView.alpha = 0;
        
        UIButton *btn_0 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn_0 setImage:[UIImage imageNamed:@"sicang_icon_copy_nor"] forState:UIControlStateNormal];
        [btn_0 setImage:[UIImage imageNamed:@"sicang_icon_copy_sel"] forState:UIControlStateSelected];
        btn_0.tag = 0;
        [_funcView addSubview:btn_0];
        
        
        UIButton *btn_1 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn_1 setImage:[UIImage imageNamed:@"sicang_icon_edit_nor"] forState:UIControlStateNormal];
        [btn_1 setImage:[UIImage imageNamed:@"sicang_icon_edit_sel"] forState:UIControlStateSelected];
        btn_1.tag = 1;
        
        
        if ([self.selectedItem.is_me isEqualToString:@"1"]) {
            
            [_funcView addSubview:btn_1];
        }
        
        UIButton *btn_2 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn_2 setImage:[UIImage imageNamed:@"sicang_icon_cut_nor"] forState:UIControlStateNormal];
        [btn_2 setImage:[UIImage imageNamed:@"sicang_icon_cut_sel"] forState:UIControlStateSelected];
        btn_2.tag = 2;
        [_funcView addSubview:btn_2];
        
        UIButton *btn_3 = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn_3 setImage:[UIImage imageNamed:@"sicang_icon_deletet_nor"] forState:UIControlStateNormal];
        [btn_3 setImage:[UIImage imageNamed:@"sicang_icon_deletet_sel"] forState:UIControlStateSelected];
        btn_3.tag = 3;
        [_funcView addSubview:btn_3];
        
        btn_0.sd_layout.heightIs(SJLayoutFrame(60));
        btn_1.sd_layout.heightIs(SJLayoutFrame(60));
        btn_2.sd_layout.heightIs(SJLayoutFrame(60));
        btn_3.sd_layout.heightIs(SJLayoutFrame(60));
        
        NSMutableArray *temp = [NSMutableArray new];
        [temp addObject:btn_0];
        [temp addObject:btn_1];
        [temp addObject:btn_2];
        [temp addObject:btn_3];
        
        [_funcView setupAutoMarginFlowItems:[temp copy] withPerRowItemsCount:temp.count itemWidth:SJLayoutFrame(60) verticalMargin:0 verticalEdgeInset:0 horizontalEdgeInset:0];
        
    }
    return _funcView;
}


- (void)funcAction:(CGPoint)point {
    
    CGPoint touchPoint = [self.view convertPoint:point toView:self.funcView];
    
    for (UIButton *btn in self.funcView.subviews) {
        
        if (CGRectContainsPoint(btn.frame, touchPoint)) {
            
            [self functionAction:btn.tag];
            break;
        } else {
            
            [self hideTrash];
            [self stopAutoScrollTimer];
            [self removeNode];
        }
    }
}

- (void)functionAction:(NSInteger)tag {
    
    if (tag == 0) { // copy
        
        [self cpToFavorite];
    } else if (tag == 1) { // edit
        
        [self editItem];
    } else if (tag == 2) { // cut
        
        [self moveToFavorite];
    } else if (tag == 3) { // delete
        
        [self deleteItem];
    }
}

- (void)deleteItem {
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"10"]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        
        [SVProgressHUD showInfoWithStatus:@"不可操作"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = item.ID;
    
    SJDelBlockApi *api = [[SJDelBlockApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            [self.dataArray removeObject:item];
            [self.collectionView deleteItemsAtIndexPaths:@[touchIndexPath]];
            
            [SVProgressHUD showSuccessWithStatus:@"删除成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        [_snapshot removeFromSuperview];
        _snapshot = nil;
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self.collectionView addGestureRecognizer:self.longPressGesture];
        
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"删除";
        attributes[@"ID"] = item.ID;
        attributes[@"content"] = item.content;
        attributes[@"fmt"] = item.fmt;
        [SJStatisticTool event:@"deleteItem" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
    }];
}


- (void)editItem {
    
    [self.imageViewer dismiss:NO];
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    [self editFilter];
    
    if ([item.fmt isEqualToString:@"1"]) { // 词条
        
        SJEditWordViewController *editVC = [SJEditWordViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    if ([item.fmt isEqualToString:@"2"]) { // 图片
        
        SJEditPicViewController *editVC = [SJEditPicViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    if ([item.fmt isEqualToString:@"3"]) { // 音频
        
        SJEditAudioViewController *editVC = [SJEditAudioViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    if ([item.fmt isEqualToString:@"4"]) { // 视频
        
        SJEditVideoViewController *editVC = [SJEditVideoViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
    
    if ([item.fmt isEqualToString:@"11"]) { // 视频
        
        SJEditTxtViewController *editVC = [SJEditTxtViewController new];
        editVC.item = item;
        editVC.optionArray = self.optionArray;
        [self.navigationController pushViewController:editVC animated:YES];
    }
  
    [self hideTrash];
    [self stopAutoScrollTimer];
    [self removeNode];
    
}


- (void)cpToFavorite {
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    if ([item.can_fav isEqualToString:@"1"]) {
        
        [SVProgressHUD showInfoWithStatus:@"内容受作者保护"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    if ([item.fmt isEqualToString:@"10"]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        
        [SVProgressHUD showInfoWithStatus:@"不可操作"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = item.ID;
    parameters[@"source"] = @"6";
    
    SJSpaceStationAddApi *api = [[SJSpaceStationAddApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [SVProgressHUD showSuccessWithStatus:@"复制成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        }
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"复制";
        attributes[@"ID"] = item.ID;
        attributes[@"content"] = item.content;
        attributes[@"fmt"] = item.fmt;
        [SJStatisticTool event:@"copyItem" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
    }];
}

- (void)moveToFavorite {
    
    NSIndexPath *touchIndexPath = [self.collectionView indexPathForItemAtPoint:self.touchPoint];
    SJWordItem *item = self.dataArray[touchIndexPath.item];
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"10"]) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
        [SVProgressHUD showInfoWithStatus:@"不可操作"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = item.ID;
    parameters[@"source"] = @"3";
    
    SJSpaceStationAddApi *api = [[SJSpaceStationAddApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            [self.dataArray removeObject:item];
            [self.collectionView deleteItemsAtIndexPaths:@[touchIndexPath]];
            
            [SVProgressHUD showSuccessWithStatus:@"剪切成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }
        
        
        [_snapshot removeFromSuperview];
        _snapshot = nil;
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self.collectionView addGestureRecognizer:self.longPressGesture];
        
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"剪切";
        attributes[@"ID"] = item.ID;
        attributes[@"content"] = item.content;
        attributes[@"fmt"] = item.fmt;
        [SJStatisticTool event:@"cutItem" attributes:attributes];
        
    } failure:^(YTKBaseRequest *request) {
        
        [self hideTrash];
        [self stopAutoScrollTimer];
        [self removeNode];
    }];
}

#pragma mark - SJUploadBarDelegate

- (void)uploadWord {
    
    BOOL flag = NO;
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] isEqualToString:@"2"]) {
            flag = YES;
            break;
        }
    }
    
    if (!flag) {
        
        [SVProgressHUD showInfoWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    SJAddWordViewController *addVC = [SJAddWordViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)uploadPicture {
    
    BOOL flag = NO;
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] isEqualToString:@"2"] && [dict[@"h"] isEqualToString:@"2"]) {
            flag = YES;
            break;
        }
    }
    
    if (!flag) {
        
        [SVProgressHUD showInfoWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    SJAddPicViewController *addVC = [SJAddPicViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)fromSS {
    
    BOOL flag = NO;
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] isEqualToString:@"2"]) {
            flag = YES;
            break;
        }
    }
    
    if (!flag) {
        
        [SVProgressHUD showInfoWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    SJAddFromSSViewController *addVC = [SJAddFromSSViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)uploadTxt {
    
    BOOL flag = NO;
    for (NSMutableDictionary *dict in self.optionArray) {
        
        if ([dict[@"w"] isEqualToString:@"2"] && [dict[@"h"] isEqualToString:@"2"]) {
            flag = YES;
            break;
        }
    }
    
    if (!flag) {
        
        [SVProgressHUD showInfoWithStatus:@"空间太小"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    SJAddTxtViewController *addVC = [SJAddTxtViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
    
}

- (void)uploadPictures {
    
    SJAddPicViewController *addVC = [SJAddPicViewController new];
    addVC.l = self.l;
    addVC.t = self.t;
    addVC.optionArray = self.optionArray;
    [self.navigationController pushViewController:addVC animated:YES];
}

- (void)uploadBar:(SJUploadBar *)uploadBar didSelectItemAtIndex:(NSInteger)index {
    
    WeakSelf;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (index == 0) { // 词条
            [weakSelf uploadWord];
        }
        
        if (index == 1) { // 文本
            [weakSelf uploadTxt];
        }
        
        if (index == 2) { // 图片
            [weakSelf uploadPicture];
        }
        
        if (index == 3) { // 从空间站选择
            [weakSelf fromSS];
        }
        
    }];
}

- (void)alertUploadBar {
    
    SJUploadBar *uploadBar = [[SJUploadBar alloc] initWithFrame:CGRectMake(0, 0, SJScreenW, SJLayoutFrame(60))];
    
    if ([self.t intValue] >= self.bottomNum) {
        uploadBar.hasPictures = YES;
    } else {
        uploadBar.hasPictures = NO;
    }
    
    uploadBar.delegate = self;
    
    WeakSelf;
    [LEEAlert actionsheet].config
    .LeeAddCustomView(^(LEECustomView *custom) {
        custom.view = uploadBar;
        custom.isAutoWidth = YES;
    })
    .LeeMaxWidth(SJScreenW)
    .LeeHeaderColor([UIColor clearColor])
    .LeeBackgroundStyleTranslucent(0)
    .LeeActionSheetBottomMargin(SJLayoutFrame(11))
    .LeeHeaderInsets(UIEdgeInsetsZero)
    .LeeCloseComplete(^{
        [weakSelf.touchView removeFromSuperview];
        weakSelf.touchView = nil;
        weakSelf.tabBarController.tabBar.hidden = NO;
    })
    .LeeShow();
    
    NSString *imageName = @"guide_new_type";
    if (812 == SJScreenH) {
        imageName = [NSString stringWithFormat:@"%@-x", imageName];
    }
    
    if ([SJGuideView shouldShowGuider:imageName]) {
        [SJGuideView guideViewWithImageName:imageName];
    }
}

- (void)addItem {
    
    // 检索
    int max_t = 0;
    for (SJWordItem *item in self.dataArray) {
        
        if ([item.t intValue] >= max_t) {
            max_t = [item.t intValue] + [item.h intValue];
        }
    }
    
    NSMutableArray *arrlt = [NSMutableArray array]; // 二维
    int max_w = SJItemCount;
    for (int i = 0; i < max_t + max_w; i++) {
        
        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [arrlt addObject:arrl];
        
        for (int j = 0; j < max_w; j++) {
            arrlt[i][j] = @0;
        }
    }
    
    for (SJWordItem *item in self.dataArray) {
        
        int t = [item.t intValue];
        int l = [item.l intValue];
        int w = [item.w intValue];
        int h = [item.h intValue];
        
        for (int i = t; i < t + h; i++) {
            
            for (int j = l; j < l + w; j++) {
                arrlt[i][j] = @1;
            }
        }
    }
    
    int l2r = 0;
    NSMutableArray *optArray = [NSMutableArray array];
    
    if ([self.t intValue] >= arrlt.count - max_w) {
        
        int maxOptW = max_w - [self.l intValue];
        int maxOptH = max_w;
        
        for (int i = 0; i < maxOptH; i++) {
            
            for (int j = 0; j < maxOptW; j++) {
                
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = [NSString stringWithFormat:@"%d", i + 1];
                dict[@"w"] = [NSString stringWithFormat:@"%d", j + 1];
                [optArray addObject:dict];
            }
        }
        
    } else {
        
        for (int i = [self.l intValue]; i < max_w; i++) { // 第1行
            
            if ([arrlt[[self.t intValue]][i] isEqualToNumber: @0]) {
                
                l2r = i - [self.l intValue] + 1;
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"h"] = @"1";
                dict[@"w"] = [NSString stringWithFormat:@"%d", l2r];
                [optArray addObject:dict];
                
            } else {
                break;
            }
        }
        
        for (int n = 1; n < max_w; n++) { // 2 ~ max_w 行
            
            for (int i = [self.l intValue]; i < max_w; i++) {
                
                if ([arrlt[[self.t intValue] + n][i] isEqualToNumber: @0]) {
                    
                    if (i - [self.l intValue] + 1 <= l2r) {
                        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                        dict[@"h"] = [NSString stringWithFormat:@"%d", n + 1];
                        dict[@"w"] = [NSString stringWithFormat:@"%d", i - [self.l intValue] + 1];
                        [optArray addObject:dict];
                    } else {
                        break;
                    }
                    
                } else {
                    l2r = i - [self.l intValue];
                    break;
                }
            }
        }
    }
    
    if (optArray.count == 0) {
        return;
    }
    
    self.optionArray = optArray;
    
    [self alertUploadBar];
    
    // 显示点击区域
    [self.collectionView addSubview:self.touchView];
    
    int lNum = [self.l intValue];
    int tNum = [self.t intValue];
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin; // 设置上面的 margin
    
    self.touchView.sd_layout
    .leftSpaceToView(self.collectionView, x)
    .topSpaceToView(self.collectionView, y)
    .heightIs(SJItemWH)
    .widthIs(SJItemWH);
}


#pragma mark - 移动相关

- (void)cellSelectedAtIndexPath:(NSIndexPath *)indexPath{
    
    SJOneCell *cell = (SJOneCell *)[self.collectionView cellForItemAtIndexPath:indexPath] ;
    
    self.selectedIndexPath = indexPath;
    self.selectedCell = cell;
    self.snapshot = [self customSnapshotFromView:cell];
    
    [self.collectionView addSubview:self.snapshot];
    
    cell.hidden = YES;
    CGPoint center = self.snapshot.center;
    center.y = self.touchPoint.y;
    center.x = self.touchPoint.x;
    WeakSelf;
    [UIView animateWithDuration:0.2 animations:^{
        weakSelf.snapshot.center = center;
    }];
}

#pragma 返回一个给定view的截图.
- (UIView *)customSnapshotFromView:(UIView *)inputView {
    
    // Make an image from the input view.
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Create an image view.
    UIView *snapshot = [[UIImageView alloc] initWithImage:image];
    snapshot.center = inputView.center;
    snapshot.layer.masksToBounds = NO;
    snapshot.layer.cornerRadius = 0.0;
    snapshot.layer.shadowOffset = CGSizeMake(-5.0, 0.0);
    snapshot.layer.shadowRadius = 5.0;
    snapshot.layer.shadowOpacity = 0.4;
    
    return snapshot;
}

/**
 拖动中调用
 */
- (void)gestureChangedAtPoint:(CGPoint)point {
    
    // 截图跟随手指移动
    CGPoint center = self.snapshot.center;
    center.y = point.y;
    center.x = point.x;
    self.snapshot.center = center;
    
    if ([self checkIfSnapshotMeetsEdge]) {
        [self startAutoScrollTimer];
    }else{
        [self stopAutoScrollTimer];
    }
}

#pragma 检查截图是否到达整个collectionView的边缘，并作出响应
- (BOOL)checkIfSnapshotMeetsEdge {
    
    CGFloat minY = CGRectGetMinY(_snapshot.frame);
    CGFloat maxY = CGRectGetMaxY(_snapshot.frame);
    if (minY < self.collectionView.contentOffset.y) {
        _autoScrollDirection = @"1";
        return YES;
    }
    if (maxY > self.collectionView.bounds.size.height + self.collectionView.contentOffset.y) {
        _autoScrollDirection = @"2";
        return YES;
    }
    return NO;
}

#pragma timer methods
/**
 *  创建定时器并运行
 */
- (void)startAutoScrollTimer{
    if (!_autoScrollTimer) {
        _autoScrollTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(startAutoScroll)];
        [_autoScrollTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    }
}
/**
 *  停止定时器并销毁
 */
- (void)stopAutoScrollTimer{
    if (_autoScrollTimer) {
        [_autoScrollTimer invalidate];
        _autoScrollTimer = nil;
    }
}

#pragma mark - 开始自动滚动
- (void)startAutoScroll {
    
    CGFloat pixelSpeed = 4;
    if ([_autoScrollDirection isEqualToString:@"1"]) { //向下滚动
        if (self.collectionView.contentOffset.y > 0) { //向下滚动最大范围限制
            [self.collectionView setContentOffset:CGPointMake(0, self.collectionView.contentOffset.y - pixelSpeed)];
            _snapshot.center = CGPointMake(_snapshot.center.x, _snapshot.center.y - pixelSpeed);
        }
    } else { //向上滚动
        if (self.collectionView.contentOffset.y + self.collectionView.bounds.size.height < self.collectionView.contentSize.height) { //向下滚动最大范围限制
            [self.collectionView setContentOffset:CGPointMake(0, self.collectionView.contentOffset.y + pixelSpeed)];
            _snapshot.center = CGPointMake(_snapshot.center.x, _snapshot.center.y + pixelSpeed);
        }
    }
}

/**
 拖动完成调用
 */
- (void)gestureEnded {
    
    [self stopAutoScrollTimer];
    [self didEndDraging];
}


/**
 *  拖拽结束，显示cell，并移除截图
 */
- (void)didEndDraging {
    
    SJWordItem *selectedItem = self.dataArray[self.selectedIndexPath.row];
    // 检索
    int max_t = 0;
    
    for (SJWordItem *item in self.dataArray) {
        
        if ([item.t intValue] >= max_t) {
            max_t = [item.t intValue] + [item.h intValue];
        }
    }
    
    NSMutableArray *arrlt = [NSMutableArray array]; // 二维
    int max_w = SJItemCount;
    
    for (int i = 0; i < max_t + max_w * 2; i++) {
        
        NSMutableArray *arrl = [NSMutableArray array]; //横向
        [arrlt addObject:arrl];
        
        for (int j = 0; j < max_w; j++) {
            arrlt[i][j] = @0;
        }
    }
    
    for (SJWordItem *item in self.dataArray) {
        
        int t = [item.t intValue];
        int l = [item.l intValue];
        int w = [item.w intValue];
        int h = [item.h intValue];
        
        if (selectedItem == item) {
            continue;
        }
        
        for (int i = t; i < t + h; i++) {
            
            for (int j = l; j < l + w; j++) {
                arrlt[i][j] = @1;
            }
        }
    }
    
    
    int l = (int)(self.snapshot.frame.origin.x / ((SJScreenW - SJMargin) / SJItemCount));
    int t = (int)((self.snapshot.frame.origin.y + SJMargin)/ ((SJScreenW - SJMargin) / SJItemCount)); // 空置 上沿
    int w = [selectedItem.w intValue];
    int h = [selectedItem.h intValue];
    
    BOOL isMove = YES;
    
    for (int i = t; i < t + h; i++) {
        
        if (l + w > max_w || l < 0 || t < 0) {
            isMove = NO;
            break;
        }
        
        for (int j = l; j < l + w; j++) {
            
            if ([arrlt[i][j] isEqualToValue:@1]) {
                
                isMove = NO;
                break;
            }
        }
    }
    
    if (isMove) { // 可以移动
        [self moveNodeWithItem:selectedItem l:l t:t];
        
    } else {  // 不可移动
        
        [SVProgressHUD showInfoWithStatus:@"位置不足"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        
        [self removeNode];
    }
}

- (void)moveNodeWithItem:(SJWordItem *)item l:(int)l t:(int)t {
    
    // 1.拼接参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"id"] = item.ID;
    parameters[@"l"] = [NSString stringWithFormat:@"%i", l];
    parameters[@"t"] = [NSString stringWithFormat:@"%i", t];
    parameters[@"h"] = item.h;
    parameters[@"w"] = item.w;
    parameters[@"pid"] = @"0";
    
    SJMovePosApi *api = [[SJMovePosApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            item.t = [NSString stringWithFormat:@"%i", t];
            item.l = [NSString stringWithFormat:@"%i", l];
            int lNum = [item.l intValue];
            int tNum = [item.t intValue];
            
            CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
            CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin;
            
            [UIView animateWithDuration:0.2 animations:^{
                _snapshot.left_sd = x;
                _snapshot.top_sd = y;
                
            } completion:^(BOOL finished) {
                [_snapshot removeFromSuperview];
                _snapshot = nil;
                [self.collectionView addGestureRecognizer:self.longPressGesture];
                [self.collectionView reloadData];
            }];
            
            
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            attributes[@"name"] = @"移动";
            attributes[@"ID"] = item.ID;
            attributes[@"content"] = item.content;
            attributes[@"fmt"] = item.fmt;
            [SJStatisticTool event:@"moveItem" attributes:attributes];
            
        } else {
            [self removeNode];
        }
        
    } failure:^(YTKBaseRequest *request) {
        [self removeNode];
    }];
}

- (void)removeNode {
    
    WeakSelf;
    [self stopAutoScrollTimer];
    [UIView animateWithDuration:0.2 animations:^{
        _snapshot.center = self.selectedCell.center;
    } completion:^(BOOL finished) {
        
        [_snapshot removeFromSuperview];
        _snapshot = nil;
        [self.collectionView addGestureRecognizer:self.longPressGesture];
        weakSelf.selectedCell.hidden = NO;
    }];
}

#pragma mark - SJCustomLayoutDelegate

- (CGRect)collectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout frameOfItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJWordItem *item = self.dataArray[indexPath.item];
    
    int lNum = [item.l intValue];
    int tNum = [item.t intValue];
    int wNum = [item.w intValue];
    int hNum = [item.h intValue];
    
    if (tNum + hNum >= self.bottomNum) {
        self.bottomNum = tNum + hNum;
    }
    
    
    CGFloat x = lNum * SJItemWH + (lNum + 1) * SJMargin;
    CGFloat y = tNum * SJItemWH + (tNum + 0) * SJMargin; // 设置上面的 margin
    CGFloat w = wNum * SJItemWH + (wNum - 1) * SJMargin;
    CGFloat h = hNum * SJItemWH + (hNum - 1) * SJMargin;
    
    return CGRectMake(x, y, w, h);
}

- (CGFloat)bottomMarginInCollectionView:(UICollectionView *)collectionView layout:(SJCustomLayout *)layout {
    
    return SJScreenW;
}


#pragma mark - UICollectionViewDataSource, UICollectionViewDelegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    // 根据数据量显示或者隐藏footer
    self.collectionView.mj_footer.hidden = (self.dataArray.count == 0);
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    SJOneCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([SJOneCell class]) forIndexPath:indexPath];
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
//    cell.isDisplayTitle = self.isDisplayTitle;
    
    cell.isDisplayTitle = @"1";
    cell.item = item;
    
    if (cell.hidden) {
        cell.hidden = NO;
    }
    
    WeakSelf;
    cell.singleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf singleTap:cell];
    };
    
    cell.doubleTapLabel = ^(UICollectionViewCell *cell) {
        
        [weakSelf doubleTap:cell];
    };
    
    return cell;
}

#pragma mark 点击 cell 的事件
- (void)doubleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"] || [item.fmt isEqualToString:@"10"]) {
        return;
    }
    
    
    self.selectedItem = item;
    
    if ([item.fmt isEqualToString:@"1"]) { // 文字
        
        [self tapText:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
        
        [self tapPic:(SJOneCell *)cell item:item];
        
    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
        
        [self tapAudio:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"音频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Audio" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
        
        [self tapVideo:(SJOneCell *)cell item:item];
        
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        attributes[@"name"] = @"视频播放";
        attributes[@"content"] = item.content;
        [SJStatisticTool event:@"play_Video" attributes:attributes];
        
    } else if ([item.fmt isEqualToString:@"10"]) { // 空间站
        
        SJSpaceStationViewController *spaceVC = [SJSpaceStationViewController new];
        spaceVC.item = item;
        [self.navigationController pushViewController:spaceVC animated:YES];
        
    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
        
        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
        txtVC.item = item;
        txtVC.hasMore = YES;
        txtVC.dataArray = self.dataArray;
        txtVC.popToVc = self;
        [self.navigationController pushViewController:txtVC animated:YES];
    }
    
    
    
//    if ([item.fmt isEqualToString:@"1"]) {
//
//        self.selectedItem = item;
//        [self tapText:(SJOneCell *)cell item:item];
//    } else {
//
//        SJTreeViewController *treeVC = [SJTreeViewController new];
//        treeVC.item = item;
//        treeVC.pageType = @"mine";
//        [self.navigationController pushViewController:treeVC animated:YES];
//
//    }
}

- (void)singleTap:(UICollectionViewCell *)cell {
    
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    
    if (indexPath.row >= self.dataArray.count) {
        return;
    }
    
    SJWordItem *item = self.dataArray[indexPath.row];
    
    if ([item.fmt isEqualToString:@"8"]) {
        return;
    }
    
    if ([item.fmt isEqualToString:@"10"]) {
        
        SJSpaceStationViewController *spaceVC = [SJSpaceStationViewController new];
        spaceVC.item = item;
        [self.navigationController pushViewController:spaceVC animated:YES];
        return;
    }
    
    SJTreeViewController *treeVC = [SJTreeViewController new];
    treeVC.item = item;
    treeVC.pageType = @"mine";
    [self.navigationController pushViewController:treeVC animated:YES];
    
    
//    self.selectedItem = item;
//
//    if ([item.fmt isEqualToString:@"1"]) { // 文字
//
//
//        SJTreeViewController *treeVC = [SJTreeViewController new];
//        treeVC.item = item;
//        treeVC.pageType = @"mine";
//        [self.navigationController pushViewController:treeVC animated:YES];
//
//
//    } else if ([item.fmt isEqualToString:@"2"]) { // 图片
//
//        [self tapPic:(SJOneCell *)cell item:item];
//
//    } else if ([item.fmt isEqualToString:@"3"]) { // 音频
//
//        [self tapAudio:(SJOneCell *)cell item:item];
//
//
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"音频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Audio" attributes:attributes];
//
//    } else if ([item.fmt isEqualToString:@"4"]) { // 视频
//
//        [self tapVideo:(SJOneCell *)cell item:item];
//
//        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
//        attributes[@"name"] = @"视频播放";
//        attributes[@"content"] = item.content;
//        [SJStatisticTool event:@"play_Video" attributes:attributes];
//
//    } else if ([item.fmt isEqualToString:@"10"]) { // 空间站
//
//        SJSpaceStationViewController *spaceVC = [SJSpaceStationViewController new];
//        spaceVC.item = item;
//        [self.navigationController pushViewController:spaceVC animated:YES];
//
//    } else if ([item.fmt isEqualToString:@"11"]) { // 文本
//
//        SJTxtDetailViewController *txtVC = [SJTxtDetailViewController new];
//        txtVC.item = item;
//        txtVC.hasMore = YES;
//        txtVC.dataArray = self.dataArray;
//        txtVC.popToVc = self;
//        [self.navigationController pushViewController:txtVC animated:YES];
//    }
    
}

- (void)tapAudio:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    SJExtraItem *extra = [SJExtraItem modelWithJSON:item.extra];
    
    if (extra.cover) {
        NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, extra.cover];
        imageInfo.imageURL = [NSURL URLWithString:urlString];
    } else {
        UIImage *img = [UIImage imageNamed:@"icn_audio"];
        imageInfo.image = img;
        imageInfo.referenceContentMode = UIViewContentModeCenter;
    }
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    self.imageViewer = imageViewer;
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    self.player = [[AVPlayer alloc] initWithURL:[NSURL URLWithString:urlString]];
    [self.player play];
}


- (void)tapVideo:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceContentMode = UIViewContentModeCenter;
    UIImage *img = [UIImage imageNamed:@"common_trans_square"];
    
    imageInfo.image = img;
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];;
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    self.imageViewer = imageViewer;
    
    // 视频
    [[JPVideoPlayerCache sharedCache] clearDiskOnCompletion:^{
        // do something  必须清了缓存？才能播放？
    }];
    
    self.videoContainer = ({
        UIView *videoView = [UIView new];
        videoView.backgroundColor = [UIColor blackColor];
        videoView.frame = CGRectMake(0, 0, SJScreenW, SJScreenW * 9.0 / 16.0);
        [imageViewer.imageView addSubview:videoView];
        
        videoView;
    });
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTapGesture:)];
    [self.videoContainer addGestureRecognizer:tapGestureRecognizer];
    self.videoContainer.jp_videoPlayerDelegate = self;
    [self.videoContainer jp_perfersPlayingProgressViewColor:SJColorHexString(@"#f76a4a")];
    [self.videoContainer jp_perfersDownloadProgressViewColor:[UIColor lightGrayColor]];
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJAvURL, self.selectedItem.content];
    [self.videoContainer jp_playVideoWithURL:[NSURL URLWithString:urlString]];
    
}

- (void)tapText:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.text = item.content;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.numberOfLines = 0;
    titleLabel.size_sd = CGSizeMake(SJScreenW - SJLayoutFrame(40), SJScreenH);
    
    UIImage *img = [titleLabel.layer snapshotImage];
    while (!img) { // 这样好吗？
        img = [titleLabel.layer snapshotImage];
    }
    
    imageInfo.image = img;
    
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    self.imageViewer = imageViewer;
    
}

- (void)tapPic:(SJOneCell *)cell item:(SJWordItem *)item {
    
    // Create image info
    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", SJImgURL, item.content];
    imageInfo.imageURL = [NSURL URLWithString:urlString];
    
    imageInfo.referenceRect = cell.frame;
    imageInfo.referenceView = cell.superview;
    imageInfo.referenceCornerRadius = 6;
    
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]
                                           initWithImageInfo:imageInfo
                                           mode:JTSImageViewControllerMode_Image
                                           backgroundStyle:JTSImageViewControllerBackgroundOption_Blurred];
    
    // Present the view controller.
    imageViewer.animationDelegate = self;
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
    self.imageViewer = imageViewer;
    
}

#pragma mark - JPVideoPlayerDelegate

- (BOOL)shouldDownloadVideoForURL:(NSURL *)videoURL{
    return YES;
}

- (BOOL)shouldProgressViewOnTop{
    return NO;
}

- (BOOL)shouldAutoReplayAfterPlayCompleteForURL:(nonnull NSURL *)videoURL {
    
    return YES;
}

- (void)playingStatusDidChanged:(JPVideoPlayerPlayingStatus)playingStatus{
    
    SJLog(@"playingStatus-----%ld", (long)playingStatus);
    
}

//- (void)downloadingProgressDidChanged:(CGFloat)downloadingProgress{
//    SJLog(@"downloadingProgress------%0.2lf", downloadingProgress);
//}
//
//- (void)playingProgressDidChanged:(CGFloat)playingProgress{
//    SJLog(@"playingProgress------%0.2lf", playingProgress);
//}

#pragma mark - Tap Event

- (void)handleTapGesture:(UITapGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateEnded) {
        if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusPortrait) {
            [self.videoContainer jp_gotoLandscapeAnimated:YES completion:^{
            }];
        }
        else if (self.videoContainer.viewStatus == JPVideoPlayerVideoViewStatusLandscape) {
            [self.videoContainer jp_gotoPortraitAnimated:YES completion:^{
            }];
        }
        
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
}

#pragma JTSImageViewControllerAnimationDelegate

- (void)imageViewerWillBeginPresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView {
    
}

- (void)imageViewerWillAnimatePresentation:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration { // 显示完 图片墙 did
    
    WeakSelf;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(duration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [weakSelf showDetaillInView:containerView];
    });
    
    
}

- (void)imageViewer:(JTSImageViewController *)imageViewer willAdjustInterfaceForZoomScale:(CGFloat)zoomScale withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
}

- (void)imageViewerWillBeginDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView { // 将要消失 图片墙 will
    
    // 删除详情
    [self hideDetaill];
    
    if ([self.selectedItem.fmt isEqualToString:@"4"]) {
        
        [self.videoContainer jp_stopPlay];
        [self.videoContainer removeFromSuperview];
        self.videoContainer = nil;
    }
    
    if ([self.selectedItem.fmt isEqualToString:@"3"]) {
        
        [self.player pause];
        self.player = nil;
    }
    
    self.imageViewer = nil;
}

- (void)imageViewerWillAnimateDismissal:(JTSImageViewController *)imageViewer withContainerView:(UIView *)containerView duration:(CGFloat)duration {
    
    
}


- (void)showDetaillInView:(UIView *)view {
    
    [view addSubview:self.detailImageView];
    self.detailImageView.sd_layout
    .heightIs(SJLayoutFrame(45))
    .leftSpaceToView(view, SJLayoutFrame(0))
    .rightSpaceToView(view, SJLayoutFrame(0))
    .bottomSpaceToView(view, SJLayoutFrame(0));
    
    SJExtraItem *extraItem = [SJExtraItem modelWithJSON:self.selectedItem.extra];
    self.detailLabel.text = extraItem.t;
    
    [UIView animateWithDuration:.25 animations:^{
        self.detailImageView.alpha = 1;
    }];
    
}

- (void)hideDetaill {
    
    [self.detailImageView removeAllSubviews];
    [self.detailImageView removeFromSuperview];
    self.detailImageView = nil;
    self.detailLabel = nil;
    
}

#pragma mark - request

- (void)loadNewData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = @"0";
    parameters[@"id"] = @"0";
    parameters[@"page"] = @"mine";
    
    SJTreeApi *api = [[SJTreeApi alloc] initWithParameters:parameters];
    
    if ([api loadCacheWithError:nil]) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"data"][@"cur"] intValue];
            
        } else {
            [self.dataArray removeAllObjects];
        }
    }
    
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            self.dataArray = [[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"][@"data"]] mutableCopy];
            self.page = [api.responseObject[@"content"][@"data"][@"cur"] intValue];
            
        } else {
            [self.dataArray removeAllObjects];
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_header endRefreshing];
    }];
    
}

- (void)loadMoreData {
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"token"] = [SJUserDefaults objectForKey:SJToken];
    parameters[@"rn"] = SJCountOfPage;
    parameters[@"pn"] = [NSString stringWithFormat:@"%d", ++self.page];
    parameters[@"id"] = @"0";
    parameters[@"page"] = @"mine";
    
    SJTreeApi *api = [[SJTreeApi alloc] initWithParameters:parameters];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        if ([api.responseObject[@"result"][@"err"] intValue] == 0) {
            
            [self.dataArray addObjectsFromArray:[NSArray modelArrayWithClass:[SJWordItem class] json:api.responseObject[@"content"][@"data"][@"data"]]];
            self.page = [api.responseObject[@"content"][@"data"][@"cur"] intValue];
            
        } else {
            self.page--;
        }
        
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        
    } failure:^(YTKBaseRequest *request) {
        [self.collectionView reloadData];
        [self.collectionView.mj_footer endRefreshing];
        self.page--;
    }];
}

#pragma mark - 登录
- (void)login {
    
    // 进入到登录注册界面
    SJRegisterViewController *registerVC = [SJRegisterViewController new];
    SJNavigationController *registerlNav = [[SJNavigationController alloc] initWithRootViewController:registerVC];
    [self presentViewController:registerlNav animated:YES completion:nil];
}

@end

